#!/usr/bin/python3
# -* - coding: UTF-8 -* -

'''
元素定位
'''
from selenium.webdriver.common.by import By
import os
import sys

curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)

from utils import SetResult
from selenium_utils.Apgar import Apgar


class ElementGps():

    def __init__(self,driver):
        self.driver = driver

    def find_element(self, type, value):
        '''
        :param type:
        :param value:
        :return:
        '''
        By.ID
        eles = self.driver.find_element(type, value)
        return eles

    def find_element_instance(self, type, value, instance):
        '''
        用于多个元素定位属性一致的时候，通过instance 来定位第几个元素
        :param type:
        :param value:
        :param instance:
        :return:
        '''
        eles = self.driver.find_elements(type, value)
        if len(eles) > instance:
            return eles[instance]

        SetResult.set_fail('未匹配到足够多的元素数量，type：{},value:{},instance:{}'.format(type, value, instance))

    def find_element_match_text(self, type, value, match_text):

        eles = self.driver.find_elements(type, value)
        if len(eles) == 0:
            SetResult.set_fail('未匹配到元素，type：{},value:{}'.format(type, value))
        for item in eles:
            if item.text == match_text:
                return item

        SetResult.set_fail('未匹配到指定文本的元素，type：{},value:{}，match_text：{}'.format(type, value, match_text))


    def find_element_by_attribute(self, type, value, attribute_name, attribute_value):
        eles = self.driver.find_elements(type, value)
        if len(eles) == 0:
            SetResult.set_fail('未匹配到元素，type：{},value:{}'.format(type, value))
        for item in eles:
            if item.get_attribute(attribute_name) == attribute_value:
                return item

        SetResult.set_fail(
            '未匹配到元素，type：{},value:{}，attribute_name：{},attribute_value:{}'.format(type, value, attribute_name,
                                                                                  attribute_value))

    def button_instance(self, button_value, instance):
        eles = self.driver.find_elements(By.XPATH, '//button')
        if len(eles) == 0:
            SetResult.set_fail('未匹配到button元素')
        index = 0
        for item in eles:
            if item.text == button_value:
                if instance == index:
                    return item
                index += 1

        SetResult.set_fail('未匹配到指定文案或instance的button，button text:{}，instance:{}'.format(button_value, instance))

    def button(self, button_value):
        return self.button_instance(button_value, 0)
